package edu.wisc.hevea.zookeeper.util;

import java.io.IOException;
import java.util.List;
import java.util.Map.Entry;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import edu.wisc.hevea.constants.ApplicationConstants;

public class ZooKeeperUtil {

	public static ZooKeeper getZooKeeperInstance(String hostname, int sessionTimeout,
			Watcher watcher) throws IOException {
		ZooKeeper zk = new ZooKeeper(hostname, sessionTimeout, watcher);
		return zk;
	}
	
	public static String getPreferredZookeeperHostName(String myHostName) {
		String zooKeeperHostName = "";
		
		String myDC = ApplicationConstants.HOST_DC_MAPPING.get(myHostName);
		for(Entry<String,String> e : ApplicationConstants.ZOOKEEPER_DC_MAPPING.entrySet()) {
			if(e.getValue().equals(myDC)) {
				zooKeeperHostName = e.getKey();
				break;
			}
		}
		
		if(zooKeeperHostName.length() == 0) {
			zooKeeperHostName = "127.0.0.1:2181";
		}
		
		return zooKeeperHostName;
	}
	
	public static String getPreferredZookeeperHostNameByDataCenter(
			String myDataCenter) {
		String zooKeeperHostName = "";

		for (Entry<String, String> e : ApplicationConstants.ZOOKEEPER_DC_MAPPING
				.entrySet()) {
			if (e.getValue().equals(myDataCenter)) {
				zooKeeperHostName = e.getKey();
				break;
			}
		}

		if (zooKeeperHostName.length() == 0) {
			zooKeeperHostName = "127.0.0.1:2181";
		}

		return zooKeeperHostName;
	}
	
	public static void createPath(ZooKeeper zooKeeper, String absolutePath,
			String data) throws KeeperException, InterruptedException {
		zooKeeper.create(absolutePath, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
				CreateMode.PERSISTENT);
	}
	
	public static void createEphemeralPath(ZooKeeper zooKeeper, String absolutePath,
			String data) throws KeeperException, InterruptedException {
		zooKeeper.create(absolutePath, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
				CreateMode.EPHEMERAL);		
	}
	
	public static boolean doesExistPath(ZooKeeper zooKeeper, String absolutePath)
			throws KeeperException, InterruptedException {
		return zooKeeper.exists(absolutePath, false) != null;
	}	
	
	public static String readData(ZooKeeper zooKeeper, String absolutePath)
			throws KeeperException, InterruptedException {
		return new String(zooKeeper.getData(absolutePath, false, null));
	}
	
	public static List<String> getChildren(ZooKeeper zooKeeper, String absolutePath, Watcher watcher)
			throws KeeperException, InterruptedException {
		return zooKeeper.getChildren(absolutePath, watcher);
	}
	
}
